import 'package:flutter/material.dart';
import 'package:netflix_social/models/social_post.dart';
import 'package:netflix_social/models/user.dart';

class SocialProvider with ChangeNotifier {
  List<SocialPost> _posts = [];
  List<SocialPost> _userPosts = [];
  List<User> _followingSuggestions = [];
  List<SocialPost> _trendingPosts = [];
  List<SocialPost> _followingPosts = [];
  List<SocialPost> _discoverPosts = [];
  bool _isLoading = false;

  List<SocialPost> get posts => _posts;
  List<SocialPost> get userPosts => _userPosts;
  List<User> get followingSuggestions => _followingSuggestions;
  List<SocialPost> get trendingPosts => _trendingPosts;
  List<SocialPost> get followingPosts => _followingPosts;
  List<SocialPost> get discoverPosts => _discoverPosts;
  bool get isLoading => _isLoading;

  // 初始化数据
  Future<void> initialize() async {
    _isLoading = true;
    notifyListeners();

    try {
      // 在实际应用中，您会从API获取这些数据
      // 这里我们使用模拟数据
      await Future.delayed(const Duration(milliseconds: 800));
      _loadMockData();
    } catch (e) {
      print('初始化社交数据时出错: $e');
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // 获取用户的帖子
  Future<void> getUserPosts(String userId) async {
    _isLoading = true;
    notifyListeners();

    try {
      // 在实际应用中，您会从API获取用户的帖子
      await Future.delayed(const Duration(milliseconds: 500));
      _userPosts = _posts.where((post) => post.author.id == userId).toList();
    } catch (e) {
      print('获取用户帖子时出错: $e');
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // 喜欢/取消喜欢帖子
  Future<bool> toggleLikePost(String postId) async {
    try {
      final postIndex = _posts.indexWhere((post) => post.id == postId);
      if (postIndex == -1) return false;

      // 在实际应用中，您会发送请求到API来更新点赞状态
      final updatedPost = _posts[postIndex].copyWith(
        isLiked: !_posts[postIndex].isLiked,
        likeCount: _posts[postIndex].isLiked
            ? _posts[postIndex].likeCount - 1
            : _posts[postIndex].likeCount + 1,
      );
      _posts[postIndex] = updatedPost;

      // 如果这个帖子也在用户帖子列表中，更新它
      final userPostIndex = _userPosts.indexWhere((post) => post.id == postId);
      if (userPostIndex != -1) {
        _userPosts[userPostIndex] = updatedPost;
      }

      notifyListeners();
      return true;
    } catch (e) {
      print('切换帖子点赞状态时出错: $e');
      return false;
    }
  }

  // 评论帖子
  Future<bool> commentOnPost(String postId, String content) async {
    try {
      final postIndex = _posts.indexWhere((post) => post.id == postId);
      if (postIndex == -1) return false;

      // 在实际应用中，您会发送请求到API来添加评论
      // 这里我们只是模拟添加一个新评论
      final newComment = Comment(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        author: User(
          id: '1',
          username: '阿明',
          email: 'aming@example.com',
          avatar: 'https://randomuser.me/api/portraits/men/32.jpg',
          membershipExpiry: DateTime(2025, 12, 31),
        ),
        content: content,
        createdAt: DateTime.now(),
      );

      final updatedComments = [..._posts[postIndex].comments, newComment];
      final updatedPost = _posts[postIndex].copyWith(
        comments: updatedComments,
        commentCount: _posts[postIndex].commentCount + 1,
      );
      _posts[postIndex] = updatedPost;

      // 如果这个帖子也在用户帖子列表中，更新它
      final userPostIndex = _userPosts.indexWhere((post) => post.id == postId);
      if (userPostIndex != -1) {
        _userPosts[userPostIndex] = updatedPost;
      }

      notifyListeners();
      return true;
    } catch (e) {
      print('评论帖子时出错: $e');
      return false;
    }
  }

  // 创建新帖子
  Future<bool> createPost({
    required String content,
    List<String> images = const [],
    String? videoId,
    String? activityType,
  }) async {
    _isLoading = true;
    notifyListeners();

    try {
      // 在实际应用中，您会发送请求到API来创建帖子
      await Future.delayed(const Duration(milliseconds: 800));

      // 创建一个新的帖子
      final newPost = SocialPost(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        author: User(
          id: '1',
          username: '阿明',
          email: 'aming@example.com',
          avatar: 'https://randomuser.me/api/portraits/men/32.jpg',
          membershipExpiry: DateTime(2025, 12, 31),
        ),
        content: content,
        images: images,
        createdAt: DateTime.now(),
        activityType: activityType,
      );

      // 添加到列表的开头
      _posts.insert(0, newPost);
      _userPosts.insert(0, newPost);

      return true;
    } catch (e) {
      print('创建帖子时出错: $e');
      return false;
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // 获取关注建议
  Future<void> getFollowingSuggestions() async {
    _isLoading = true;
    notifyListeners();

    try {
      // 在实际应用中，您会从API获取关注建议
      await Future.delayed(const Duration(milliseconds: 400));
      
      // 在这里使用模拟数据
      _followingSuggestions = [
        User(
          id: '2',
          username: '小红',
          email: 'xiaohong@example.com',
          avatar: 'https://randomuser.me/api/portraits/women/44.jpg',
          followersCount: 562,
          followingCount: 231,
          membershipExpiry: DateTime(2024, 5, 15),
        ),
        User(
          id: '3',
          username: '大卫',
          email: 'david@example.com',
          avatar: 'https://randomuser.me/api/portraits/men/86.jpg',
          followersCount: 1203,
          followingCount: 98,
          membershipExpiry: DateTime(2024, 8, 22),
        ),
        User(
          id: '4',
          username: '小美',
          email: 'xiaomei@example.com',
          avatar: 'https://randomuser.me/api/portraits/women/68.jpg',
          followersCount: 892,
          followingCount: 345,
          membershipExpiry: DateTime(2024, 10, 30),
          isVerified: true,
        ),
      ];
    } catch (e) {
      print('获取关注建议时出错: $e');
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // 关注/取消关注用户
  Future<bool> toggleFollowUser(String userId) async {
    try {
      // 在实际应用中，您会发送请求到API来更新关注状态
      // 这里我们只是模拟状态变化
      await Future.delayed(const Duration(milliseconds: 300));
      
      // 在实际应用中，您可能会更新用户的关注者和关注中的计数
      // 以及在UI中反映这些更改
      
      return true;
    } catch (e) {
      print('切换关注状态时出错: $e');
      return false;
    }
  }

  // 根据视频ID获取相关帖子
  List<SocialPost> getPostsByVideoId(String videoId) {
    // 在实际应用中，您会从API获取与特定视频相关的帖子
    // 这里我们只是过滤现有的帖子列表
    return _posts.where((post) => post.relatedVideo?.id == videoId).toList();
  }

  // 点赞/取消点赞
  Future<bool> toggleLike(String postId) async {
    try {
      final postIndex = _posts.indexWhere((post) => post.id == postId);
      if (postIndex == -1) return false;

      // 切换点赞状态
      final currentPost = _posts[postIndex];
      final updatedPost = currentPost.copyWith(
        isLiked: !currentPost.isLiked,
        likeCount: currentPost.isLiked 
          ? currentPost.likeCount - 1 
          : currentPost.likeCount + 1,
      );

      // 更新帖子
      _posts[postIndex] = updatedPost;
      
      // 同步更新各个分类列表中的帖子
      _updatePostInLists(postId, updatedPost);
      
      notifyListeners();
      return true;
    } catch (e) {
      print('切换点赞状态时出错: $e');
      return false;
    }
  }
  
  // 在各个列表中更新帖子
  void _updatePostInLists(String postId, SocialPost updatedPost) {
    // 更新趋势帖子列表
    final trendingIndex = _trendingPosts.indexWhere((post) => post.id == postId);
    if (trendingIndex != -1) {
      _trendingPosts[trendingIndex] = updatedPost;
    }
    
    // 更新关注帖子列表
    final followingIndex = _followingPosts.indexWhere((post) => post.id == postId);
    if (followingIndex != -1) {
      _followingPosts[followingIndex] = updatedPost;
    }
    
    // 更新发现帖子列表
    final discoverIndex = _discoverPosts.indexWhere((post) => post.id == postId);
    if (discoverIndex != -1) {
      _discoverPosts[discoverIndex] = updatedPost;
    }
    
    // 更新用户帖子列表
    final userPostIndex = _userPosts.indexWhere((post) => post.id == postId);
    if (userPostIndex != -1) {
      _userPosts[userPostIndex] = updatedPost;
    }
  }

  // 加载模拟数据
  void _loadMockData() {
    // 用户
    final xiaohong = User(
      id: '2',
      username: '小红',
      email: 'xiaohong@example.com',
      avatar: 'https://randomuser.me/api/portraits/women/44.jpg',
      followersCount: 562,
      followingCount: 231,
      membershipExpiry: DateTime(2024, 5, 15),
    );

    final aming = User(
      id: '1',
      username: '阿明',
      email: 'aming@example.com',
      avatar: 'https://randomuser.me/api/portraits/men/32.jpg',
      followersCount: 843,
      followingCount: 125,
      watchCount: 286,
      membershipType: '黄金会员',
      membershipExpiry: DateTime(2025, 12, 31),
      isVerified: true,
    );

    final xiaomei = User(
      id: '4',
      username: '小美',
      email: 'xiaomei@example.com',
      avatar: 'https://randomuser.me/api/portraits/women/68.jpg',
      followersCount: 892,
      followingCount: 345,
      membershipExpiry: DateTime(2024, 10, 30),
      isVerified: true,
    );

    // 模拟社交帖子
    _posts = [
      SocialPost(
        id: '1',
        author: xiaohong,
        content: '推荐一部超棒的科幻电影！《流浪地球2》剧情紧张刺激，特效也非常震撼！中国科幻电影终于崛起了！#科幻电影 #流浪地球',
        images: ['https://images.unsplash.com/photo-1626814026160-2237a95fc5a0'],
        createdAt: DateTime.now().subtract(const Duration(hours: 2)),
        likeCount: 128,
        commentCount: 36,
        shareCount: 12,
        comments: [
          Comment(
            id: '101',
            author: aming,
            content: '确实很不错，特效水平提升很大！',
            createdAt: DateTime.now().subtract(const Duration(hours: 1, minutes: 30)),
            likeCount: 8,
          ),
          Comment(
            id: '102',
            author: xiaomei,
            content: '我也很喜欢，期待第三部！',
            createdAt: DateTime.now().subtract(const Duration(hours: 1)),
            likeCount: 5,
          ),
        ],
      ),
      SocialPost(
        id: '2',
        author: aming,
        content: '我的本周观影打卡第6天！今天终于看完了《满江红》，沈腾的演技真的提升很大，期待他更多的作品。#观影打卡 #满江红',
        images: ['https://images.unsplash.com/photo-1533613220915-609f661a6fe1'],
        createdAt: DateTime.now().subtract(const Duration(days: 1, hours: 14)),
        likeCount: 86,
        commentCount: 14,
        shareCount: 3,
        isLiked: true,
        activityType: '观影打卡',
        comments: [
          Comment(
            id: '201',
            author: xiaohong,
            content: '沈腾真的很有演技，不只是喜剧演员那么简单',
            createdAt: DateTime.now().subtract(const Duration(days: 1, hours: 13)),
            likeCount: 12,
          ),
        ],
      ),
      SocialPost(
        id: '3',
        author: xiaomei,
        content: '【重磅】影享圈年度会员特惠开始了！4月会员日活动，年卡7折，还有专属观影券赠送！点击了解详情👇 #会员特惠 #限时优惠',
        createdAt: DateTime.now().subtract(const Duration(days: 3)),
        likeCount: 352,
        commentCount: 89,
        shareCount: 126,
        activityType: '官方活动',
        comments: [
          Comment(
            id: '301',
            author: aming,
            content: '这个活动真的很划算，我已经续费了！',
            createdAt: DateTime.now().subtract(const Duration(days: 2, hours: 20)),
            likeCount: 5,
          ),
          Comment(
            id: '302',
            author: xiaohong,
            content: '请问可以用优惠券吗？',
            createdAt: DateTime.now().subtract(const Duration(days: 2, hours: 18)),
            likeCount: 0,
          ),
          Comment(
            id: '303',
            author: xiaomei,
            content: '@小红 可以的，活动期间所有优惠可叠加使用',
            createdAt: DateTime.now().subtract(const Duration(days: 2, hours: 17)),
            likeCount: 2,
          ),
        ],
      ),
    ];

    // 初始化用户帖子
    _userPosts = _posts.where((post) => post.author.id == '1').toList();
  }
}
